/* eslint-disable array-callback-return,no-undef */
import fetch from 'dva/fetch';
import React, { Component } from 'react';
import { Layout, Tabs, Form, Modal, Spin, message, Avatar } from 'antd';
import styles from '../../../index.less';
import Toolbar from '../../Common/ToolBar/ToolBar';
import TabMainTable from './TabMainTable';
import TabProbably from './TabProbably';
import TabContacts from './TabContacts';
import TabAddress from './TabAddress';
import * as config from '../../../utils/config';
import * as dropdownstatic from '../../../utils/dropdownstatic';
import * as commonFunc from '../../Common/commonFunc';
import baseHigher from '../../Common/baseHigher';
import PpopupPan from '../../../routes/ppopupPan/ppopupPan';
import imgInvalid from '../../../assets/haveCancel.png';

const { confirm } = Modal;
const { Header, Content } = Layout;
const { TabPane } = Tabs;

class CustomerInfoComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      btnData: config.btnData, /* 工具栏按钮 */
      masterConfig: { sId: '' }, // 主表 + 从表 配置
      sId: '', /* 业务数据ID */
      sActiveId: '', /* 窗体Id */
      disabled: false, /* 是否是查看状态 */
      loading: false,
      modalVisible: false, /* 弹窗显示状态 */
      modalPanel: {}, /* 弹窗面板属性 */
      mainTable: '', /* 主表 */
      tableConfig: '', /* 数据表 */
      tabProbably: '', /* 概览 */
      tabContacts: '', /* 联系人 */
      tabAddress: '', /* 地址 */
      contactData: [],
      contactDataSave: [],
      addressData: [],
      addressDataSave: [],
      customerData: {},
      listRecordKey: { contactDataKey: '', addressDataKey: '' }, /* 列表弹窗当前操作行,内部属性根据模块不同自定义 */
      sTabId: '', /* Tab页ID用于复制到等功能新弹出窗口避免弹出多个窗口 */
      newIdlength: 0, /* 复制到所用到的从表ID数 */
      newIdFlag: true, /* 页面复制数据后刷新渲染 */
      bDefaultFlag: false, /* 省市区默认是否有勾选 */
      bDefaultEd: false, /* 联系人默认是否有勾选 */
      sListFormmasterId: '',
      sFormmasterId: '',
      configureMap: '',
      sFilterOrderBy: '',
      bFilter: '',
      currentData: [],
      pages: {},
      pageSize: '',
      iCountSum: '',
      formData: [],
      currentIndex: '',
      btnDataAll: [],
      gdsformconst: [], /* 常量 */
      currentIndexFlag: false,
      count: 0, /* 从表总行数 */
      report: [], /* 打印报表 */
    };
  }

  componentWillReceiveProps(nextProps) {
    const { dataList } = nextProps.content;
    const { gdsformconst, report } = nextProps;
    if (this.state.gdsformconst.length === 0) {
      this.setState({
        gdsformconst,
      });
    }
    if (this.state.report.length === 0) {
      const btnDataChild = [];
      report.forEach((child, i) => {
        btnDataChild.push({
          sName: `BtnPrint.${i}`,
          showName: child.sReportName,
          bVisible: true,
          sActiveId: '',
          sId: child.sId,
        });
      });
      this.setState({ btnDataChild, report });
    }
    /* 配置 */
    const {
      sDataListTabId, urlData, formRoute, loading, sId, paneType, checkedId, disabled, sParentId, newIds, sFilterOrderBy, bFilter, pageSize, pages, sListFormmasterId, currentData, newkey,
    } = dataList;
    if (urlData !== undefined && Object.keys(urlData).length > 0 && paneType !== undefined && paneType !== '' && nextProps.sTabId === sParentId) {
      const paneKey = new Date().getTime().toString();
      const pane = {
        copyToData: dataList.copyToData, /* 复制到数据 */
        title: urlData.sMenuName,
        route: urlData.sName,
        formId: urlData.sId,
        checkedId,
        disabled,
        key: paneKey,
        sFilterOrderBy,
        bFilter,
        pageSize,
        pages,
        sListFormmasterId,
        currentData,
        newkey,
      };
      this.props.onAddPane(pane);
      return;
    }
    /* 数据Id */
    const { formId } = nextProps;
    /* 窗体全部配置 */
    const masterConfig = commonFunc.getWindowConfig('elecustomer', nextProps.formData);
    /* 弹出窗数据返回,渲染数据并关闭弹出框 */
    if ((nextProps.app.ppopupPane !== undefined &&
        nextProps.app.ppopupPane.mainConfig !== undefined) ? (nextProps.sTabId === nextProps.app.ppopupPane.mainConfig.key
        && nextProps.formRoute === nextProps.app.ppopupPane.mainConfig.route) : false) {
      const { resultValue } = nextProps.app.ppopupPane;
      const { modalType } = nextProps.app.ppopupPane;
      /* 通用弹窗数据返值处理 */
      if ((resultValue !== undefined) && modalType === 'ppopup') {
        /* 数据集名 */
        const { dataName } = nextProps.app.ppopupPane;
        /* 数据集类型，对象型为Map 数组型为List */
        const { dataType } = nextProps.app.ppopupPane;
        const data = this.state[`${dataName}`];
        if (dataType === 'Map') {
          for (const key of Object.keys(resultValue)) {
            data[`${key}`] = resultValue[`${key}`];
          }
          this.setState({ [`${dataName}`]: data, modalVisible: false });
        } else if (dataType === 'List') {
          data.map((item) => {
            if ((item.sId === undefined ? item.key : item.sId) === this.state.listRecordKey[`${dataName}Key`]) {
              for (const key of Object.keys(resultValue)) {
                /* 赋值回带配置为#字段#,需取主表相应字段值 */
                if (typeof (resultValue[`${key}`]) === 'string' && resultValue[`${key}`].startsWith('#') && resultValue[`${key}`].endsWith('#')) {
                  item[`${key}`] = this.state.customerData[`${key}`];
                } else {
                  item[`${key}`] = resultValue[`${key}`];
                }
              }
            }
            return item;
          });
          /* 弹窗数据回填后，清空listRecordKey 避免数据污染 */
          this.setState({
            [`${dataName}`]: data,
            modalVisible: false,
            listRecordKey: { contactDataKey: '', addressDataKey: '' },
          });
        }
        /* 弹出框关闭 */
        this.props.onRemoveModalPane({});
        return;
      }
    }
    if (nextProps.sTabId === sDataListTabId && nextProps.formRoute === formRoute && nextProps.formData.length > 0) {
      if (loading) {
        this.setState({ loading: true });
        return;
      }
      if (dataList.returnType !== undefined && dataList.returnType === 'CUD') {
        if (sId !== undefined && sId !== '') {
          this.setState({ sId });
        }
        this.setState({ disabled: dataList.disabled });
        this.handleRefresh(sId);
        return;
      }
      /* 窗体显示配置 */
      const masterShowConfig = commonFunc.getConfigCondition(masterConfig.gdsconfigformslave, 'bVisible');
      if (this.state.sActiveId === '') {
        const materielPan = nextProps.app.currentPane;
        /* 获取工具栏, 主表，页签标题 */
        this.setState({ toolProps: nextProps });
        const { formData } = urlData;
        /* 窗体配置 */
        const mainTable = formData.filter(item => (item.sTbName.toLowerCase() === 'elecustomer'))[0];
        /* 匹配主表 */
        const mainConfig = mainTable.gdsconfigformslave;
        const tabProbably = mainConfig.filter(item => (item.sControlName.toLowerCase() === 'tabprobably'))[0];
        const tabContacts = mainConfig.filter(item => (item.sControlName.toLowerCase() === 'tabcontacts'))[0];
        const tabAddress = mainConfig.filter(item => (item.sControlName.toLowerCase() === 'tabaddress'))[0];
        /* 从表配置 */
        this.setState({
          formData,
          mainTable,
          disabled: materielPan.disabled !== undefined ? materielPan.disabled : false,
          sId: materielPan.checkedId !== undefined ? materielPan.checkedId : '',
          sActiveId: formId,
          tabProbably: tabProbably !== undefined ? tabProbably
            : { showName: '概览', sId: new Date().getTime() + 1 }, /* 页签名 */
          tabContacts: tabContacts !== undefined ? tabContacts : { showName: '联系人', sId: new Date().getTime() + 2 },
          tabAddress: tabAddress !== undefined ? tabAddress : { showName: '地址', sId: new Date().getTime() + 3 },
          sFilterOrderBy: materielPan.sFilterOrderBy,
          bFilter: materielPan.bFilter,
          currentData: materielPan.currentData,
          sListFormmasterId: materielPan.sListFormmasterId,
          pageSize: materielPan.pageSize,
          pages: materielPan.pages,
          currentIndex: materielPan.newKey !== undefined ? materielPan.newKey.split('-')[materielPan.newKey.split('-').length - 1] : '',
        });
        if (materielPan.copyToData !== undefined) {
          const copyToData = JSON.parse(JSON.stringify(materielPan.copyToData));
          let newIdCount = 0;
          for (const value of Object.keys(copyToData)) {
            /* 是否数组 */
            if (!Array.isArray(copyToData[value])) {
              copyToData[value].sId = '';
            } else {
              for (const v of copyToData[value]) {
                v.handleType = 'add';
                newIdCount += 1;
              }
            }
          }
          this.setState({ ...copyToData, newIdlength: newIdCount });
        }
        this.setState({ masterConfig, masterShowConfig });
      } else if (dataList.returnType !== undefined && dataList.returnType === 'data'
        && dataList.componentName.indexOf('elecustomercontacts') <= -1
        && dataList.componentName.indexOf('elecustomeraddress') <= -1) {
        const customerData = Object.keys(urlData).length > 0
          ? urlData[0] : {};
        const cProCityArea = [];
        /* 主表省市区拼接显示 */
        cProCityArea[0] = customerData.sProvince !== undefined ? customerData.sProvince : '';
        cProCityArea[1] = customerData.sCity !== undefined ? customerData.sCity : '';
        cProCityArea[2] = customerData.sArea !== undefined ? customerData.sArea : '';
        customerData.cProCityArea = cProCityArea;
        /* 从表默认状态匹配勾选 */
        this.setState({ customerData, loading: false, sTabId: nextProps.sTabId });
      } else if (newIds !== undefined) {
        const { contactData, addressData } = this.state;
        const ids = newIds;
        for (const v of contactData) {
          [v.sId] = ids;
          ids.splice(0, 1);
        }
        for (const v of addressData) {
          [v.sId] = ids;
          ids.splice(0, 1);
        }
        this.setState({
          contactData, addressData, newIdlength: 0, newIdFlag: false,
        });
      }
      if (dataList.returnType !== undefined
        && dataList.returnType === 'data'
        && dataList.componentName === 'elecustomercontacts') {
        const contactDataSave = Object.keys(urlData).length > 0
          ? urlData : [];
        const { count } = this.state;
        if (contactDataSave.length < count) {
          this.handleSpaceAdd(contactDataSave, nextProps.formData, 'elecustomercontacts', 'contactData');
        } else {
          this.setState({ contactData: contactDataSave });
        }
        this.setState({ loading: false, contactDataSave });
      }
      if (dataList.returnType !== undefined
        && dataList.returnType === 'data'
        && dataList.componentName === 'elecustomeraddress') {
        const addressDataSave = Object.keys(urlData).length > 0
          ? urlData : [];
        for (const item of addressDataSave) {
          /* 给省市区伪字段赋值 */
          const cProCityArea = [];
          cProCityArea[0] = item.sProvince;
          cProCityArea[1] = item.sCity;
          cProCityArea[2] = item.sArea;
          item.cProCityArea = cProCityArea;
        }
        const { count } = this.state;
        if (addressDataSave.length < count) {
          this.handleSpaceAdd(addressDataSave, nextProps.formData, 'elecustomeraddress', 'addressData');
        } else {
          this.setState({ addressData: addressDataSave });
        }
        this.setState({ loading: false, addressDataSave });
      }
    }
  }

  shouldComponentUpdate(nextProps, nextState) {
    let flag = true;
    /* 追加弹出框数值回填放行判断ppopupPane */
    if (nextProps.sTabId === nextProps.app.currentPane.key || ((nextProps.app.ppopupPane !== undefined
        && nextProps.app.ppopupPane.mainConfig !== undefined)
      ? nextProps.sTabId === nextProps.app.ppopupPane.mainConfig.key : false)) {
      if (nextState.disabled !== this.state.disabled) {
        return true;
      }
      flag = true;
    } else {
      flag = false;
    }
    return flag;
  }

  handleCount = (count) => {
    this.setState({ count });
  };

  handleSpaceAdd = (data, formData, sTabName, sFormData) => {
    const { count } = this.state;
    const subjectTable = formData.filter(item => (item.sTbName.toLowerCase() === sTabName))[0];
    const subjectConfig = subjectTable.gdsconfigformslave;
    let totalRow = false;
    /* 取出汇总列 */
    subjectConfig.map((child) => {
      if (child.bSum) {
        totalRow = true;
      }
      return child;
    });
    const difCount = totalRow ? count - data.length - 1 : count - data.length;
    const { token } = this.props.app;
    const url = `${config.server_host}getUuid/${difCount}`;
    const options = {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
    };
    /* 获取表头 */
    const headerConfig = [];
    for (const child of subjectConfig) {
      if (child.sName !== '' && child.bVisible && child.showName !== '') {
        headerConfig.push({
          title: child.showName,
          dataIndex: child.sName,
          width: child.iFitWidth,
        });
      }
    }
    const newRow = [];
    fetch(url, options).then(response => response.json()).then((json) => {
      if (json.code === 1) {
        const keys = json.dataset.rows;
        for (let i = 0; i < keys.length; i += 1) {
          const newData = {
            key: keys[i],
          };
          headerConfig.forEach((slaveChild) => {
            const ckey = slaveChild.dataIndex;
            const showConfig = subjectConfig.filter(item => (item.sName === ckey))[0];
            /* 新增一行的默认值添加进列表提交数据 */
            const columnValue = commonFunc.listDefaultValueNewAdd(showConfig, '');
            newData[ckey] = columnValue;
          });
          newRow.push({ ...newData, handleType: 'add' });
        }
        const subjectData = [...data, ...newRow];
        this.setState({ [sFormData]: subjectData });
      }
    });
  };

  handleSubjectDataSave = (subjectData) => {
    /* 实际保存的数据 */
    const subjectDataSave = [];
    for (const child of subjectData) {
      let flag = 0;
      for (const key in child) {
        if (key !== 'key' && key !== 'handleType' && key !== 'sId' && key !== 'sParentId' && key.substring(0, 1) !== 'b') {
          if (key !== 'cProCityArea') {
            if (child[key] !== '' && parseFloat(child[key] * 1) !== 0) {
              flag = 1;
              break;
            }
          } else if (child.cProCityArea !== undefined && child.cProCityArea.length > 0) {
            flag = 1;
            break;
          }
        }
      }
      if (flag === 1) {
        subjectDataSave.push(child);
      }
    }
    return subjectDataSave;
  };

  /* 刷新 */
  handleRefresh = (newsId) => {
    const { dispatch } = this.props;
    const {
      masterConfig, sId, sActiveId, formData,
    } = this.state;
    let id = sId;
    if (newsId !== undefined && newsId !== '') {
      id = newsId;
    }
    if (id !== undefined && id !== '') {
      /* 表Id */
      const mainId = masterConfig.sId;
      /* 业务数据Id */
      const value = { sId: id };
      const sTabId = this.props.app.currentPane.key;
      /* 从表value */
      const slaveValue = {
        sSqlCondition: {
          sParentId: id,
        },
      };
      const contactConfig = formData.filter(item => (item.sTbName.toLowerCase() === 'elecustomercontacts'))[0];
      const addressConfig = formData.filter(item => (item.sTbName.toLowerCase() === 'elecustomeraddress'))[0];
      const contactsId = contactConfig.sId;
      const addresssId = addressConfig.sId;
      const mainDataUrl =
        `${config.server_host}business/getBusinessDataByFormcustomId/${mainId}?sModelsId=${sActiveId}`;
      dispatch({
        type: 'content/getUrlPostData',
        payload: {
          url: mainDataUrl,
          sTabId,
          componentName: 'elecustomer',
          value,
          formRoute: '/elecustomer',
          returnType: 'data',
        },
      });
      const contactDataUrl =
        `${config.server_host}business/getBusinessDataByFormcustomId/${contactsId}?sModelsId=${sActiveId}`;
      dispatch({
        type: 'content/getUrlPostData',
        payload: {
          url: contactDataUrl,
          sTabId,
          componentName: 'elecustomercontacts',
          value: slaveValue,
          formRoute: '/elecustomercontacts',
          returnType: 'data',
        },
      });
      const addressDataUrl =
        `${config.server_host}business/getBusinessDataByFormcustomId/${addresssId}?sModelsId=${sActiveId}`;
      dispatch({
        type: 'content/getUrlPostData',
        payload: {
          url: addressDataUrl,
          sTabId,
          componentName: 'elecustomeraddress',
          value: slaveValue,
          formRoute: '/elecustomeraddress',
          returnType: 'data',
        },
      });
    } else {
      /* 应清空所有组件,或刷新不做任何处理或屏蔽刷新按钮 */
    }
  };

  handlePrintChild = (sId) => {
    const { formData } = this.state;
    const { token } = this.props.app;
    const { sActiveId } = this.state;
    const sMainTableId = formData[0].sId;
    const queryFilter = {};
    formData.map((item) => {
      const sDataId = item.sId;
      queryFilter[sDataId] = sDataId === sMainTableId ? { sId: this.state.sId } : {
        sSqlCondition: {
          sParentId: this.state.sId,
        },
      };
    });
    const sReportId = sId;
    const queryFilterJson = escape(JSON.stringify(queryFilter));
    const urlPrint = `${config.server_host}printReport/printPdf/${sReportId}?queryFilter=${queryFilterJson}&sModelsId=${sActiveId}&sMaintableId=${sMainTableId}&token=${encodeURIComponent(token)}`;
    window.open(urlPrint);
  };

  /* 获取上一条下一条首条末条 */
  handleSearchData = (sValue) => {
    const { sActiveId } = this.state;
    const { token } = this.props.app;
    const {
      sListFormmasterId, sFilterOrderBy, bFilter, formData, pages, pageSize, currentIndex, currentIndexFlag,
    } = this.state;
    let currentIndexPop = currentIndexFlag ? currentIndex : ((pages.pageNum - 1) * pageSize) + Number.parseInt(currentIndex, 10);
    if (sValue === 'first') {
      currentIndexPop = 1;
    } else if (sValue === 'end') {
      currentIndexPop = pages.totalCount;
    }
    const url = `${config.server_host}business/getBusinessDataByIndex?sModelsId=${sActiveId}`;
    const arrayForm = {};
    formData.forEach((child) => {
      const keys = child.sId;
      arrayForm[`${keys}`] = keys;
    });
    const value = {
      sClientType: '1',
      sListFormmasterId,
      sFormmasterId: formData[0].sId,
      currentPosition: currentIndexPop,
      configureMap: arrayForm,
      sHandleType: sValue,
      iCountSum: pages.totalCount,
    };
    if (bFilter !== undefined && bFilter !== '' && Object.keys(bFilter).length > 0) {
      value.push({ bFilter });
    }
    if (sFilterOrderBy !== undefined && sFilterOrderBy !== '' && Object.keys(sFilterOrderBy).length > 0) {
      value.push({ sFilterOrderBy });
    }
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
      body: JSON.stringify(value),
    };
    fetch(url, options).then(response => response.json()).then((json) => {
      if (json.code === 1) {
        const values = json.dataset.rows[0];
        const currentPostion = values.currentPosition;
        formData.forEach((child) => {
          const sMainId = child.sId;
          const sMainTableName = child.sTbName;
          if (sMainTableName === 'elecustomer') {
            this.setState({
              customerData: values[sMainId][0],
              sId: values[sMainId][0].sId,
            });
          } else if (sMainTableName === 'elecustomercontacts') {
            this.setState({
              contactData: values[sMainId],
            });
          } else if (sMainTableName === 'elecustomeraddress') {
            this.setState({
              addressData: values[sMainId],
            });
          }
        });
        this.setState({
          currentIndex: currentPostion,
          currentIndexFlag: true,
        });
      } else {
        message.error(json.msg);
      }
    });
  };
  /* 新增 */
  handleAdd = () => {
    /* Tab标签Id */
    this.setState({
      customerData: { bInvalid: false },
      contactData: [],
      contactDataSave: [],
      addressData: [],
      addressDataSave: [],
      disabled: false,
      sId: '',
    });
    const { formData } = this.state;
    this.handleSpaceAdd([], formData, 'elecustomercontacts', 'contactData');
    this.handleSpaceAdd([], formData, 'elecustomeraddress', 'addressData');
  };
  /* 修改 */
  handleEdit = (obj) => {
    const { disabled } = obj;
    const { customerData, gdsformconst } = this.state;
    const sToVoidEdit = gdsformconst.filter(item => (item.sName === 'sToVoidEdit'));
    if (customerData.bInvalid === true) {
      message.warning(sToVoidEdit[0].showName);
      return;
    }
    this.setState({ disabled });
  };
  /* 删除 */
  handleDel = () => {
    const onhandleOk = this.handleOk;
    const { sId } = this.state;
    const { token } = this.props.app;
    const { sActiveId } = this.state;
    confirm({
      title: '确定要删除?',
      onOk() {
        const value = {
          data: {
            sMasterTable: 'elecustomer',
            sId: [sId],
            sSlaveTable: [
              {
                tableName: 'elecustomercontacts',
                relationName: 'sParentId',
              }, {
                tableName: 'elecustomeraddress',
                relationName: 'sParentId',
              }],
          },
          sClientType: '1',
        };
        const options = {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            authorization: token,
          },
          body: JSON.stringify(value),
        };
        const url = `${config.server_host}business/delMasSlaBusinessData?sModelsId=${sActiveId}`;
        fetch(url, options).then(response => response.json()).then((json) => {
          if (json.code === 1) {
            message.success(json.msg);
            onhandleOk();
          } else {
            message.error(json.msg);
          }
        });
      },
      onCancel() {},
    });
  };

  handleInvalidOk = () => {
    const { customerData } = this.state;
    customerData.bInvalid = true;
    this.setState({
      customerData,
    });
  };

  /* 作废 */
  handleInvalid = () => {
    const onInvalidOk = this.handleInvalidOk;
    const { sId } = this.state;
    const { token } = this.props.app;
    const { sActiveId } = this.state;
    confirm({
      title: '确定要作废?',
      onOk() {
        const value = {
          sTableName: 'elecustomer',
          sId: [sId],
          sHandleType: 'toVoid',
          sClientType: '1',
        };
        const options = {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            authorization: token,
          },
          body: JSON.stringify(value),
        };
        const url = `${config.server_host}checkModel/updatebInvalid?sModelsId=${sActiveId}`;
        fetch(url, options).then(response => response.json()).then((json) => {
          if (json.code === 1) {
            message.success(json.msg);
            onInvalidOk();
          } else {
            message.error(json.msg);
          }
        });
      },
      onCancel() {},
    });
  };

  handleInvalidCancel = () => {
    const { customerData } = this.state;
    customerData.bInvalid = false;
    this.setState({
      customerData,
    });
  };

  /* 取消作废 */
  handleCancelInvalid = () => {
    const onInvalidCancel = this.handleInvalidCancel;
    const { sId } = this.state;
    const { token } = this.props.app;
    const { sActiveId } = this.state;
    confirm({
      title: '确定要取消作废?',
      onOk() {
        const value = {
          sTableName: 'elecustomer',
          sId: [sId],
          sHandleType: 'cancel',
          sClientType: '1',
        };
        const options = {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            authorization: token,
          },
          body: JSON.stringify(value),
        };
        const url = `${config.server_host}checkModel/updatebInvalid?sModelsId=${sActiveId}`;
        fetch(url, options).then(response => response.json()).then((json) => {
          if (json.code === 1) {
            message.success(json.msg);
            onInvalidCancel();
          } else {
            message.error(json.msg);
          }
        });
      },
      onCancel() {},
    });
  };
  /* 取消 */
  handleCancel =(type) => {
    const onhandleOk = this.handleOk;
    confirm({
      title: '确定要取消?',
      onOk() {
        onhandleOk(type);
      },
      onCancel() {},
    });
  };
  /* 非列表联动下拉 */
  handleSelectChange = (value, dataType, dataName) => {
    /* 数据集类型，对象型为Map 数组型为List */
    const data = this.state[`${dataName}`];
    if (dataType === 'Map') {
      for (const item of value) {
        data[`${item.key}`] = item.value;
      }
      this.setState({ [`${dataName}`]: data });
    }
  };
  /* 数据自动变更 */
  handleFormChange = (value) => {
    const key = Object.keys(value)[0];
    const { customerData } = this.state;
    const { masterShowConfig } = this.state;
    const showConfig = masterShowConfig.filter(item => (item.sName === key))[0];
    if (showConfig !== undefined && showConfig.sDropDownType === 'sql') return;
    /* 数据处理,手动清空数据时数据会为undefined，不符合数据赋值要求 */
    const changeValue = commonFunc.changeValue(value);
    this.setState({
      customerData: { ...customerData, ...changeValue },
    });
  };
  /* 确认取消 */
  handleOk = () => {
    let lastIndex = -1;
    this.props.app.panes.forEach((pane, i) => {
      if (pane.key === this.props.app.currentPane.key) {
        lastIndex = i - 1;
      }
    });

    const panes = this.props.app.panes.filter(pane => pane.key !== this.props.app.currentPane.key);
    let currentPane;
    if (lastIndex >= 0) {
      currentPane = panes[lastIndex];
    } else if (lastIndex === -1 && panes.length > 0) {
      currentPane = panes[lastIndex + 1];
    } else {
      currentPane = { title: '', route: '', key: '0' };
    }
    this.props.onRemovePane(panes, currentPane);
  };
  /* 保存 */
  handleSubmit() {
    const { dispatch, app } = this.props;
    const { currentPane } = app;
    /* 业务数据Id */
    const sTabId = currentPane.key;
    this.form.validateFieldsAndScroll((err, formValue) => {
      if (!err) {
        const { contactData, addressData } = this.state;
        const contactDataSave = this.handleSubjectDataSave(contactData);
        const addressDataSave = this.handleSubjectDataSave(addressData);
        const stateFormValue = this.state.customerData;
        const inputValue = { ...formValue, ...stateFormValue };
        /* 省市区赋值(由于有默认不操作的情况，所以把赋值放到保存里 */
        const { cProCityArea } = inputValue;
        [inputValue.sProvince] = cProCityArea;
        inputValue.sCity = cProCityArea[1] !== undefined ? cProCityArea[1] : '';
        inputValue.sArea = cProCityArea[2] !== undefined ? cProCityArea[2] : '';
        const { sActiveId } = this.state;
        const dataUrl = `${config.server_host}business/addUpdateDelBusinessData?sModelsId=${sActiveId}`;
        if (this.state.sId !== '') {
          inputValue.handleType = 'update';
          const value = {
            data: [{
              sTable: 'elecustomer',
              column: [inputValue],
            }, {
              sTable: 'elecustomercontacts',
              column: contactDataSave,
            }, {
              sTable: 'elecustomeraddress',
              column: addressDataSave,
            }],
            sClientType: '1',
          };
          dispatch({
            type: 'content/getUrlPostData',
            payload: {
              url: dataUrl,
              sTabId,
              value,
              componentName: 'elecustomer',
              formRoute: '/elecustomer',
              returnType: 'CUD',
            },
          });
        } else {
          inputValue.handleType = 'add';
          const options = {
            method: 'GET',
            headers: {
              'Content-Type': 'application/json',
            },
          };
          const url = `${config.server_host}getUuid`;
          fetch(url, options).then(response => response.json()).then((json) => {
            if (json.code === 1) {
              const sId = json.dataset.rows[0];
              inputValue.sId = sId;
              /* 把新增时获取的唯一主键放在STATE中用于成功后刷新动作 */
              inputValue.maxBillNo = 'sCustomerNo';
              for (const item of contactDataSave) {
                item.sParentId = sId;
              }
              for (const item of addressDataSave) {
                item.sParentId = sId;
              }
              const value = {
                data: [{
                  sTable: 'elecustomer',
                  column: [inputValue],
                }, {
                  sTable: 'elecustomercontacts',
                  column: contactDataSave,
                }, {
                  sTable: 'elecustomeraddress',
                  column: addressDataSave,
                }],
                sClientType: '1',
              };
              dispatch({
                type: 'content/getUrlPostData',
                payload: {
                  url: dataUrl,
                  sTabId,
                  value,
                  componentName: 'elecustomer',
                  formRoute: '/elecustomer',
                  returnType: 'CUD',
                  sId,
                },
              });
              /*   清除全局变量   */
              dropdownstatic.clearDropDownStorage('sCustomerId');
              /*   渲染   */
              dispatch({
                type: 'app/changePaneData',
                payload: {
                  parentId: currentPane.sParentId, /*   父页面编号   */
                  showRender: ['sCustomerId'], /*   主表渲染对象   */
                  showSlaveRender: [], /*   从表渲染对象   */
                  editTableRender: false, /*   从表渲染控制   */
                  isRender: false, /*   是否从高阶渲染   */
                  isRenderPart: true, /*   是否进行部分渲染   */
                },
              });
            }
          });
        }
      }
    });
  }
  /* 联系人表单自动变更 */
  handleContactData = (value, key, sSearch, column) => {
    const contactDataState = [...this.state.contactData];
    const contactDataDel = contactDataState.filter(item => (item.handleType === 'del'));
    const contactData = [...contactDataDel, ...value];
    for (const item of contactData) {
      item.sParentId = this.state.sId;
      if (key !== undefined) {
        const sId = item.key !== undefined ? item.key : item.sId;
        if (key === sId && column === 'bDefault') {
          /* 更改主表的联系人 */
          const { customerData } = this.state;
          customerData.sContacts = item.sContacts;
          customerData.sPhone1 = item.sPhone1;
          customerData.sPhone2 = item.sPhone2;
          customerData.sMobile = item.sMobile;
          customerData.sEmail = item.sEmail;
          customerData.sFax = item.sFax;
          this.setState({ customerData, bDefaultEd: true });
        } else {
          item.bDefault = false;
          item.handleType = item.handleType === 'add' ? 'add' : 'update';
        }
      }
    }
    const contactDataSave = this.handleSubjectDataSave(contactData);
    this.setState({
      contactData,
      contactDataSave,
    });
  };
  /* 地址表单自动变更 */
  handleAddressData = (value, key, sSearch, column) => {
    for (const item of value) {
      const cProCityArea = item.cProCityArea !== undefined ? item.cProCityArea : [];
      /* 默认checkbox赋值, 主表省市区更改 */
      if (key !== undefined) {
        const sId = item.key !== undefined ? item.key : item.sId;
        if (key === sId && column === 'bDefault') {
          /* 更改主表的省市区 */
          const { customerData } = this.state;
          customerData.cProCityArea = item.cProCityArea;
          customerData.sProvince = item.sProvince;
          customerData.sCity = item.sCity;
          customerData.sArea = item.sArea;
          customerData.sCompanyAddress = item.sDetailAddress;
          this.setState({ customerData, bDefaultFlag: true });
        } else {
          item.bDefault = false;
          item.handleType = item.handleType === 'add' ? 'add' : 'update';
        }
      }
      /* 省市区赋值 */
      if (cProCityArea.length > 0) {
        [item.sProvince] = cProCityArea;
        item.sCity = cProCityArea[1] !== undefined ? cProCityArea[1] : '';
        item.sArea = cProCityArea[2] !== undefined ? cProCityArea[2] : '';
      }
    }
    const addressDataState = [...this.state.addressData];
    const addressDataDel = addressDataState.filter(item => (item.handleType === 'del'));
    const addressData = [...addressDataDel, ...value];
    for (const item of addressData) {
      item.sParentId = this.state.sId;
    }
    const addressDataSave = this.handleSubjectDataSave(addressData);
    this.setState({
      addressData,
      addressDataSave,
    });
  };

  handleForm = (form) => {
    this.form = form;
  };

  /* 弹窗关闭 */
  handlePpopUpPaneCancel = () => {
    /* 弹窗类型，下拉/弹窗 */
    const { modalType } = this.props.app.ppopupPane;
    /* 数据集名 */
    const { dataName } = this.props.app.ppopupPane;
    const data = this.state[`${dataName}`];
    /* 如果为下拉新增则下拉值重置为空 */
    if (modalType === 'select') {
      /* 数据集类型，对象型为Map 数组型为List */
      const { dataType } = this.props.app.ppopupPane;
      const { mainKey } = this.props.app.ppopupPane;
      /* 窗体关闭时下拉重置为空,避免下拉项停留在NEW选项 */
      if (dataType === 'Map' && data[`${mainKey}`] === '000') {
        data[`${mainKey}`] = ' ';
      } else if (dataType === 'List') {
        data.map((item) => {
          if (item.key === this.state.listRecordKey[`${dataName}Key`] && item[`${mainKey}`] === '000') {
            item[`${mainKey}`] = ' ';
          }
          return item;
        });
      }
    }
    /* 置空models中弹窗面板 */
    this.props.onRemoveModalPane({});
    /* 隐藏弹窗面板 */
    this.setState({
      modalVisible: false,
      [`${dataName}`]: data,
      listRecordKey: { contactDataKey: '', addressDataKey: '' },
    });
  };

  /* 弹窗面板状态更改 */
  handleModalPane = (value) => {
    this.setState({ modalVisible: value.modalVisible, modalPanel: value });
  };

  /* 用于返回列表编辑框弹窗所属行主键 */
  handleRecordKey = (value) => {
    const { listRecordKey } = this.state;
    this.setState({ listRecordKey: { ...listRecordKey, ...value } });
  };

  /* 用于从表新增时判断主表必填字段是否填写 */
  handleSlaveAdd = () => {
    const { sCustomerName } = this.state.customerData;
    if (sCustomerName === undefined) {
      const { masterShowConfig } = this.state;
      const { showName } = masterShowConfig.filter(item => (item.sName === 'sCustomerName'))[0];
      message.warning(`${showName}不能为空!`);
      return true;
    } else {
      return false;
    }
  };

  handleCopyTo = () => {
    const { customerData, gdsformconst } = this.state;
    const sToVoidCopy = gdsformconst.filter(item => (item.sName === 'sToVoidCopy'));
    const sToCopyLimit = gdsformconst.filter(item => (item.sName === 'sToCopyLimit'));
    if (customerData.bInvalid === true) {
      message.warning(sToVoidCopy[0].showName);
      return;
    }
    if (customerData.bCopyLimit === true) {
      message.warning(sToCopyLimit[0].showName);
      return;
    }
    const { dispatch } = this.props;
    /* Tab标签Id */
    const paneKey = new Date().getTime().toString();
    /* 窗体Id */
    const { sActiveId } = this.state;
    const sNameUrl = `${config.server_host}gdsmodule/getGdsmoduleById/${sActiveId}?sModelsId=${sActiveId}`;
    dispatch({
      type: 'content/getUrlData',
      payload: {
        url: sNameUrl, sTabId: paneKey, urlDataType: 'newPane', disabled: false, sParentId: this.state.sTabId, copyToData: { customerData: this.state.customerData, contactData: this.state.contactData, addressData: this.state.addressData },
      },
    });
  };

  render() {
    const { pageLoading } = this.props;
    const { props, state } = this;
    const { loading } = this.state;
    return (
      <div>
        <Spin spinning={loading}>
          {pageLoading ? '' :
          <div>
            <CustomerComponent
              {...props}
              {...state}
              handleSubmit={this.handleSubmit.bind(this)}
              handleEdit={this.handleEdit.bind(this)}
              handleAdd={this.handleAdd.bind(this)}
              handleOk={this.handleOk.bind(this)}
              handleCancel={this.handleCancel.bind(this)}
              handleRefresh={this.handleRefresh.bind(this)}
              handleDel={this.handleDel.bind(this)}
              onChange={this.handleFormChange.bind(this)}
              handleForm={this.handleForm.bind(this)}
              handleContactData={this.handleContactData.bind(this)}
              handleCopyTo={this.handleCopyTo.bind(this)}
              handleAddressData={this.handleAddressData.bind(this)}
              handleModalPane={this.handleModalPane.bind(this)}
              handleRecordKey={this.handleRecordKey.bind(this)}
              handleSelectChange={this.handleSelectChange.bind(this)}
              onSlaveAdd={this.handleSlaveAdd.bind(this)}
              onInvalid={this.handleInvalid.bind(this)}
              onCancelInvalid={this.handleCancelInvalid.bind(this)}
              onNext={this.handleSearchData.bind(this, 'next')}
              onPrior={this.handleSearchData.bind(this, 'up')}
              onFirst={this.handleSearchData.bind(this, 'first')}
              onLast={this.handleSearchData.bind(this, 'end')}
              onPrintChild={this.handlePrintChild}
              onCount={this.handleCount}
              onModalClose={this.handlePpopUpPaneCancel}
            />
            <Modal
              title={Object.keys(this.state.modalPanel).length > 0 ? this.state.modalPanel.title : ''}
              visible={this.state.modalVisible}
              onCancel={this.handlePpopUpPaneCancel.bind(this)}
              footer={null}
              width={1000}
              wrapClassName={styles.modal}
            >
              <div className={styles.popupPan} id="popupPan">
                <PpopupPan handleGetResult={this.handleGetResult} />
              </div>
            </Modal>
          </div>}
        </Spin>
      </div>
    );
  }
}
const CustomerComponent = Form.create({
  mapPropsToFields(props) {
    const { customerData, masterShowConfig } = props;
    const obj = commonFunc.mapPropsToFieldsChangeValue(masterShowConfig, customerData, Form);
    return obj;
  },
  onValuesChange(props, changedFields) {
    props.onChange(changedFields);
  },
})((props) => {
  const { app, form } = props;
  const {
    sActiveId,
    masterConfig,
    sId,
    formData,
    dispatch,
    disabled,
    handleRefresh,
    handleEdit,
    handleCancel,
    handleSubmit,
    handleAdd,
    handleCopyTo,
    handleDel,
    changeDataFlag,
    handleModalPane,
    handleSelectChange,
    content,
    handleContactData,
    handleAddressData,
    handleRecordKey,
    contactData,
    addressData,
    listRecordKey,
    customerData,
    newIdlength,
    newIdFlag,
    onSlaveAdd,
    bDefaultFlag,
    bDefaultEd,
    onInvalid,
    onCancelInvalid,
    onNext,
    onPrior,
    onFirst,
    onLast,
    btnDataChild,
    onPrintChild,
    onCount,
    gdsformconst,
  } = props;
  /* 主表 */
  const { handleForm, onModalClose } = props;
  const onClose = onModalClose;
  const childProps = {
    app, form, sActiveId, sId, disabled, dispatch, content, masterConfig, handleModalPane, handleSelectChange, gdsformconst, onClose,
  };
  const mainProps = {
    formData,
    componentName: 'elecustomer',
    ...childProps,
    changeDataFlag,
    dataName: 'customerData',
    dataType: 'Map',
    dataSet: customerData,
    // contactData,
    addressData,
    newIdlength,
    newIdFlag,
  };
  /* 页签 */
  const { tabProbably, tabContacts, tabAddress } = props;
  /* 联系人表配置 refreshList用于弹窗数据回填后需要放行刷新动作 dataList列表数据下放 */
  const contactConfig = formData.filter(item => (item.sTbName.toLowerCase() === 'elecustomercontacts'))[0];
  const contactProps = {
    formData,
    componentName: 'elecustomercontacts',
    ...childProps,
    handleRecordKey,
    handleContactData,
    masterConfig: contactConfig !== undefined ? contactConfig : { sId: '' },
    dataExist: Object.keys(contactData).length > 0,
    dataName: 'contactData',
    dataType: 'List',
    dataList: contactData,
    refreshList: listRecordKey.contactDataKey === '',
    onSlaveAdd,
    onInvalid,
    onCancelInvalid,
    onNext,
    onPrior,
    onFirst,
    onLast,
    onPrintChild,
    customerData,
    bDefaultEd,
    onCount,
  };
  /* 地址表配置 refreshList用于弹窗数据回填后需要放行刷新动作 dataList列表数据下放 */
  const addressConfig = formData.filter(item => (item.sTbName.toLowerCase() === 'elecustomeraddress'))[0];
  const addressProps = {
    formData,
    componentName: 'elecustomeraddress',
    ...childProps,
    handleAddressData,
    handleRecordKey,
    masterConfig: addressConfig !== undefined ? addressConfig : { sId: '' },
    dataExist: Object.keys(addressData).length > 0,
    dataName: 'addressData',
    dataType: 'List',
    dataList: addressData,
    refreshList: listRecordKey.addressDataKey === '',
    customerData,
    bDefaultFlag,
    onCount,
    onSlaveAdd,
  };
  const bShow = customerData.bInvalid;
  let imgOption = '';
  if (bShow) {
    imgOption = <Avatar src={imgInvalid} />;
  }
  return (
    <Form>
      <Layout>
        <Header className={styles.header}>
          <Toolbar
            componentName="toolcustomer"
            {...props}
            onAdd={handleAdd}
            onEdit={handleEdit}
            onBtnDel={handleDel}
            onBtnCancel={handleCancel}
            onRefresh={handleRefresh}
            onSubmit={handleSubmit}
            onCopyTo={handleCopyTo}
            onBtnInvalid={onInvalid}
            onBtnCancelInvalid={onCancelInvalid}
            onNext={onNext}
            onBtnPrior={onPrior}
            onBtnFirst={onFirst}
            onBtnLast={onLast}
            btnDataChild={btnDataChild}
            onBtnPrintChild={onPrintChild}
          >
            {handleForm(form)}
          </Toolbar>
        </Header>
        <Layout className={styles.clayout}>
          <Content className={styles.content}>
            <TabMainTable {...mainProps} />
            <div id="slaveTabs" className={bShow ? styles.bShow : ''}>
              <div style={{ display: bShow ? 'block' : 'none' }}>
                {imgOption}
              </div>
              <Tabs className={styles.slaveTabs}>
                <TabPane tab={tabProbably.showName} key={tabProbably !== '' ? tabProbably.sId : 2} >
                  <TabProbably {...mainProps} />
                </TabPane>
                <TabPane tab={tabContacts.showName} key={tabContacts !== '' ? tabContacts.sId : 3} forceRender>
                  <TabContacts {...contactProps} />
                </TabPane>
                <TabPane tab={tabAddress.showName} key={tabAddress !== '' ? tabAddress.sId : 4} forceRender>
                  <TabAddress {...addressProps} />
                </TabPane>
              </Tabs>
            </div>
          </Content>
        </Layout>
      </Layout>
    </Form>
  );
});

export default baseHigher(CustomerInfoComponent);

